package com.gis.aoitest.state;

import com.gis.aoitest.beans.SensorReading;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class StateTest04_KeyedStateAPP2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // socket文本流
        DataStreamSource<String> inputStream = env.socketTextStream("localhost", 9999);

        // 转换成SensorReading类型
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        } );

        // 定义一个flatmap操作，检测温度跳变，输出报警
        SingleOutputStreamOperator<String> resultMap = dataStream.keyBy("id")
//                .map(new TempChangeWarningMap(10.0));
        .process(new TempChangeProcess(10.0));
        resultMap.print();



        env.execute();
    }

    public static class TempChangeWarningMap extends RichMapFunction<SensorReading, Tuple3<String, Double, Double>>{
        private double threshold;
        public TempChangeWarningMap(double threshold){
            this.threshold = threshold;
        }

        private ValueState<Double> lastTempState;

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTempState = getRuntimeContext().getState(new ValueStateDescriptor<Double>("last-temp", Double.class));
        }

        @Override
        public Tuple3<String, Double, Double> map(SensorReading sensorReading) throws Exception {
            // 获取上次温度
            Double lastTemp = lastTempState.value();

            // 比较温度
            if (lastTemp != null){
                if (Math.abs(sensorReading.getTemperature() - lastTemp) > threshold){
                    lastTempState.update(sensorReading.getTemperature());
                    return new Tuple3<>(sensorReading.getId(), lastTemp, sensorReading.getTemperature());
                }
            }

            lastTempState.update(sensorReading.getTemperature());
            return new Tuple3<>();
        }

        @Override
        public void close() throws Exception {
            lastTempState.clear();
        }
    }


    public static class TempChangeProcess extends KeyedProcessFunction<Tuple, SensorReading, String>{

        private double threshold;
        public TempChangeProcess(double threshold) {
            this.threshold = threshold;
        }

        private ValueState<Double> lastTempState;
        @Override
        public void open(Configuration parameters) throws Exception {
            lastTempState = getRuntimeContext().getState(new ValueStateDescriptor<>("last-temp", Double.class));

        }

        @Override
        public void processElement(SensorReading value, KeyedProcessFunction<Tuple, SensorReading, String>.Context ctx, Collector<String> out) throws Exception {
            // 获取last-temp
            Double lastTemp = lastTempState.value();

            // 判断是否为null
            if (lastTemp != null) {
                if (Math.abs(value.getTemperature() - lastTemp) > threshold){
                    out.collect(value.getId() + "告警了, (此次温度 - 上次温度) -> (" + value.getTemperature() + " - " + lastTemp + ");" );
                }
            }
            lastTempState.update(value.getTemperature());
        }

        @Override
        public void close() throws Exception {
            lastTempState.clear();
        }
    }
}
